﻿
"use strict";

function getDomainFromUrl(url){
	let host = "null";
	if(typeof url == "undefined" || null == url)
		url = window.location.href;
	let regex = /.*\:\/\/([^\/]*).*/;
	let match = url.match(regex);
	if(typeof match != "undefined" && null != match)
		host = match[1];
	return host;
}
var ip = "";
function checkForValidUrl(tabId, changeInfo, tab) {
	if((tab.url.indexOf("sellercentral.amazon")>0
		||tab.url.indexOf("sellercentral-europe.amazon.com")>0 )
		&&tab.url.indexOf("ap/signin")>0){
		
		chrome.pageAction.show(tabId);

		let url = localStorage.getItem("apiUrl");
		let name = localStorage.getItem("shopName");
		if( url && name ){
			let show = {
				name:name,
				type:"amazon-show"
			}
			chrome.tabs.sendMessage(tabId, show);
		}

		if(ip == ''){
			$.ajax({
				type:'GET',
				url:'http://yar999.tk/ip.php',
				success:function(data){
					if($(data)[2]){
						ip = $(data)[2].data.trim();
						//console.log(ip);
					}
				}
			});	
		}

	}
};
chrome.tabs.onUpdated.addListener(checkForValidUrl);

chrome.runtime.onMessage.addListener(function(request, sender, sendRequest){
	if(request.type === "amazon-login"){
		login(request);
	} 
});

function login(request){
	chrome.tabs.query({active:true, currentWindow: true}, function(tab) {
		let url = getDomainFromUrl(tab[0].url);
		let source = url.substr(url.length-2,2);
		if(source == "om") source = "us";
		if(url == "sellercentral-europe.amazon.com") source = "eu";

		let data = {
			acc		:	request.acc,
			pwd		:	$.md5(request.pwd),
			shop	:	request.shop,
			source	:	source,
			url		:	url,
			ip      :   ip
		}
	
		$.ajax({
			type: 'POST'
			,url: localStorage.getItem("apiUrl")
			,data: data
			,dataType: 'json'
			,success: function(res){
				if(res.state==200){
					let desPwd = DES3.decrypt(res.data.p);

					let json = {
						e:res.data.e,
						p:desPwd,
						type:"amazon-login-success"
					}
					chrome.tabs.sendMessage(tab[0].id, json);
					
					chrome.notifications.create(null, {
						type: 'basic',
						iconUrl: 'icon/icon.png',
						title: '登录成功',
						message: '登录工号：' + request.acc + 
								'\n登录店铺：' + source.toUpperCase() + '_' + request.shop.toUpperCase(),
					});

					let views = chrome.extension.getViews({type:'popup'});
					if(views && views.length>0){
						views[0].close();	
					}
				}else{
					let msg  = {
						msg  : res.msg,
						type : "amazon-error" 
					}
					chrome.tabs.sendMessage(tab[0].id, msg);
				}	
			}
			,error: function(e, m){
			  	let msg  = {
					msg  : '数据请求异常:'+m,
					type : "amazon-error" 
				}
				chrome.tabs.sendMessage(tab[0].id, msg);
			}
		});
	});
}
